<template>
  <div class="update" style="padding:40px;">
    <el-card shadow="never">
      <div slot="header">
        <span>{{ articalId?'修改文章':'新增文章' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="作者" prop="author" size="small">
              <el-input v-model="form.author" placeholder="作者姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="标题" style="width:100%" prop="title" size="small">
              <el-input v-model="form.title" placeholder="文章标题" />
            </el-form-item>
          </el-col>
          <el-col :span="6" :offset="0">
            <!-- isShow (integer, optional): 是否显示: 0 否; 1 是 , -->
            <el-form-item label="是否显示" prop="isShow" size="small">
              <el-switch v-model="form.isShow" :active-value="1" :inactive-value="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="17" :offset="0">
            <el-form-item label="摘要" size="normal">
              <el-input
                v-model="form.summary"
                type="textarea"
                :rows="3"
                placeholder="摘要"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="封面图片" size="normal">
              <el-upload
                ref="imgUpload"
                :action="uploadImageUrl"
                :headers="token"
                :on-success="uploadCoverImgSuccess"
                :before-upload="beforeCoverImgUpload"
              >
                <el-button size="small" type="primary">点击上传素材</el-button>
                <div slot="tip" class="el-upload__tip">只能上传图片文件,且不超过1.5M</div>

              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="" size="normal">
              <img v-if="form.coverImg" width="100" height="100" :src="form.coverImg" alt="">

            </el-form-item>

          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="切换富文本类型" size="normal">
              <!-- editorType (integer, optional): 编辑器类型: 0 富文本; 1 markdown , -->
              <el-radio v-model="form.editorType" :label="0" @change="changeEditorType">富文本</el-radio>
              <el-radio v-model="form.editorType" :label="1" @change="changeEditorType">markdown</el-radio>
              <span style="color:#e6a23c;"><i class="el-icon-warning" />注意!切换编辑器会清空编辑内容</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <Tinymce v-if="form.editorType===0" v-model="form.content1" style="margin-top:20px" />
            <mavon-editor v-if="form.editorType===1" ref="markdown" v-model="form.content1" @imgAdd="$imgAdd" />
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="2" :offset="10">
            <el-button style="margin-top:10px;" type="primary" size="default" @click="submit">{{ articalId?'立即修改':'立即新增' }}</el-button>
          </el-col>
        </el-row>

      </el-form>

    </el-card>

  </div>
</template>

<script>
import {
  updateArticle as updateArticleApi,
  addArticle as addArticleApi,
  productArticle as productArticleApi
} from '@/api/content/index'
import mix from '@/mixin/index'
import axios from 'axios'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'AddOrModifyArtical',
  components: {
    Tinymce
  },
  mixins: [mix],
  data() {
    return {
      articalId: '',
      form: {
        isShow: 1,
        coverImg: '',
        editorType: 0
      },
      rules: {
        author: [{ required: true, trigger: 'blur', message: '请填写作者名字' }],
        title: [{ required: true, trigger: 'blur', message: '请填写标题名称' }]
      }
    }
  },
  created() {
    this.articalId = this.$route.query.articalId
    this.getArticalDetail()
  },

  methods: {
    // 获取文章明细
    getArticalDetail() {
      if (this.articalId) {
        productArticleApi(this.articalId)
          .then(res => {
            this.form = res.data.productArticle
          })
      }
    },
    $imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      formdata.append('file', $file)
      var _this = this
      axios({
        url: _this.uploadImageUrl,
        method: 'post',
        data: formdata,
        headers: _this.token
      }).then((res) => {
        // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
        /**
               * $vm 指为mavonEditor实例，可以通过如下两种方式获取
               * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
               * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
               */

        const { data, success, message } = res.data
        if (success) {
          _this.$refs.markdown.$img2Url(pos, data.fileUrl)
        } else {
          _this.$message.error(message)
        }
      })
    },
    // 更改文本类型的时候
    changeEditorType() {
      this.form.content1 = ''
    },
    // 保存或者更新文章
    submit() {
      this.$refs.form.validate((valid, error) => {
        if (valid) { // 表格验证成功
          if (this.form.editorType === 0) { // 富文本
            this.form.content2 = this.form.content1
          } else { // markdown
            this.form.content2 = this.$refs.markdown.d_render
          }
          var api = null
          if (this.articalId) { // 修改文章
            api = updateArticleApi
            this.id = this.articalId
          } else { // 新增文章
            api = addArticleApi
          }

          api(this.form)
            .then(res => {
              this.$router.push({ name: 'Artiacl' })
            })
        } else { // 验证失败
          // console.log('error===>', error)
          for (var key in error) {
            if (error[key]) {
              const message = error[key][0].message
              this.$message.error(message)
              return
            }
          }
          return false
        }
      })
    },
    // 文件上传成功时候的钩子函数
    uploadCoverImgSuccess(res, file, fileList) {
      const { success, message, data } = res
      if (success) {
        this.form.coverImg = data.fileUrl
        this.$refs.imgUpload.clearFiles()
      } else {
        this.$message.error(message)
      }
    },
    // 在文件上传之前的钩子函数
    beforeCoverImgUpload(file) {
      // const isJPG = file.type === 'image/jpeg'
      const isLt1dot5M = file.size / 1024 / 1024 < 1.5
      var reg = /^image\/(jpe?g|png|webp|gif)$/

      const isImage = reg.test(file.type)
      if (!isImage) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt1dot5M) {
        this.$message.error('上传头像图片大小不能超过 1.5MB!')
      }
      return isImage && isLt1dot5M
    }
  }
}
</script>

<style>

</style>
